package com.example.cscot.ui.normal;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.cscot.LewayHelper;
import com.example.cscot.R;
import com.example.cscot.WeiLe;
import com.example.cscot.databinding.FragmentNormalBinding;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

public class NormalFragment extends Fragment {
    private FragmentNormalBinding binding;
    public TextView mTvBody;
    public TextView mTvQuestions;
    int mMaxLines = 0;
    int mMaxWidth = 0;
    Button mBtn1;
    Button mBtn2;
    Button mBtn3;
    Button mBtn4;
    Button mBtn5;
    String[] mQ;
    char [] mA;

    public static String TS() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd日HH:mm:ss.SSS "));
    }
    //
    // 未解之谜，如果连续两次加载长题目，就会出现layout变化，scroll失效，重新加载空文件可恢复
    // 以后再解这个问题
    public void bodyAppend(String body) {
        mTvBody.setText("");
        // mTvBody.setHeight(mMaxHeight);
        // 先找题目，算法和题目的文件格式相关
        String[] lines = body.split("\\n");
        int i = 0;
        for (i = 0; i < lines.length - 3; i++) {
            mTvBody.append(lines[i] + "\n");
            if ((lines[i+2].length() > 2) && (lines[i+2].substring(0, 2).equals("[A")) &&
                    (lines[i+3].length() > 2) && (lines[i+3].substring(0, 2).equals("[B"))) {
                break;
            }
        }
        // 再找问题，每个选项必须是每行以A. B. C. D.开头，每个选项只占一行
        int iq = 1;
        for (; i < lines.length - 3; i++) {
            if ((lines[i+1].length() > 2) && (lines[i+1].substring(0, 2).equals("[A")) &&
                    (lines[i+2].length() > 2) && (lines[i+2].substring(0, 2).equals("[B"))) {
                mQ[iq] = lines[i] + "\n" + lines[i+1] + "\n" + lines[i+2] + "\n" +
                        lines[i+3] + "\n" + lines[i+4] + "\n";
                iq += 1;
            }
        }
        // 再找答案：答案 B A A B C
        int ia = 1;
        for (; i < lines.length; i++) {
            if (lines[i].contains("答案")) {
                // 一个中文只算一个？反正只能+2，不能+4
                for (int j = lines[i].indexOf("答案") + 2; j < lines[i].length(); j++) {
                    if (('A' <= lines[i].toCharArray()[j]) && (lines[i].toCharArray()[j] <= 'D')) {
                        mA[ia] = lines[i].toCharArray()[j];
                        WeiLe.gLogText += TS() + ia + " answer=" + mA[ia] + "\n";
                        ia++;
                    }
                }
                break;
            }
        }
        // 处理完毕
    }

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        NormalViewModel normalViewModel =
                new ViewModelProvider(this).get(NormalViewModel.class);

        binding = FragmentNormalBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        mQ = new String[6];             // 第0个不用
        mA = "ZZZZZZ".toCharArray();    // 答案为必错的
        mTvBody = root.findViewById(R.id.tvBody);
        mTvBody.setMovementMethod(ScrollingMovementMethod.getInstance());
        mTvQuestions = root.findViewById(R.id.tvQuestions);
        mTvQuestions.setMovementMethod(ScrollingMovementMethod.getInstance());

        Button btn;
        btn = root.findViewById(R.id.btnPicture);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WeiLe.mainActivity.showToast("Not implemented yet, please be patient to wait.");
            }
        });
        btn = root.findViewById(R.id.btnQ1);
        mBtn1 = btn;
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (WeiLe.gBtn != null && WeiLe.gBtn != mBtn1) { // 仅在不同按钮时复原颜色
                    WeiLe.gBtn.setBackgroundColor(0xff2177b8);   // 复原颜色
                }
                WeiLe.gQid = 1;
                WeiLe.gBtn = mBtn1;
                mBtn1.setBackgroundColor(Color.GRAY);
                mBtn1.setText(String.valueOf(WeiLe.gAnswer[1]));
                if (mQ[1] != null) {
                    mTvQuestions.setText(mQ[1]);
                }
                mTvBody.setMaxLines(mMaxLines);
                mTvBody.setMaxWidth(mMaxWidth);
                mTvQuestions.setMaxWidth(mMaxWidth);
            }
        });
        btn = root.findViewById(R.id.btnQ2);
        mBtn2 = btn;
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (WeiLe.gBtn != null && WeiLe.gBtn != mBtn2) { // 仅在不同按钮时复原颜色
                    WeiLe.gBtn.setBackgroundColor(0xff2177b8);   // 复原颜色
                }
                WeiLe.gQid = 2;
                WeiLe.gBtn = mBtn2;
                mBtn2.setBackgroundColor(Color.GRAY);
                mBtn2.setText(String.valueOf(WeiLe.gAnswer[2]));
                if (mQ[2] != null) {
                    mTvQuestions.setText(mQ[2]);
                }
                mTvBody.setMaxLines(mMaxLines);
                mTvBody.setMaxWidth(mMaxWidth);
                mTvQuestions.setMaxWidth(mMaxWidth);
            }
        });
        btn = root.findViewById(R.id.btnQ3);
        mBtn3 = btn;
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (WeiLe.gBtn != null && WeiLe.gBtn != mBtn3) { // 仅在不同按钮时复原颜色
                    WeiLe.gBtn.setBackgroundColor(0xff2177b8);   // 复原颜色
                }
                WeiLe.gQid = 3;
                WeiLe.gBtn = mBtn3;
                mBtn3.setBackgroundColor(Color.GRAY);
                mBtn3.setText(String.valueOf(WeiLe.gAnswer[3]));
                if (mQ[3] != null) {
                    mTvQuestions.setText(mQ[3]);
                }
                mTvBody.setMaxLines(mMaxLines);
                mTvBody.setMaxWidth(mMaxWidth);
                mTvQuestions.setMaxWidth(mMaxWidth);
            }
        });
        btn = root.findViewById(R.id.btnQ4);
        mBtn4 = btn;
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (WeiLe.gBtn != null && WeiLe.gBtn != mBtn4) { // 仅在不同按钮时复原颜色
                    WeiLe.gBtn.setBackgroundColor(0xff2177b8);   // 复原颜色
                }
                WeiLe.gQid = 4;
                WeiLe.gBtn = mBtn4;
                mBtn4.setBackgroundColor(Color.GRAY);
                mBtn4.setText(String.valueOf(WeiLe.gAnswer[4]));
                if (mQ[4] != null) {
                    mTvQuestions.setText(mQ[4]);
                }
                mTvBody.setMaxLines(mMaxLines);
                mTvBody.setMaxWidth(mMaxWidth);
                mTvQuestions.setMaxWidth(mMaxWidth);
            }
        });
        btn = root.findViewById(R.id.btnQ5);
        mBtn5 = btn;
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (WeiLe.gBtn != null && WeiLe.gBtn != mBtn5) { // 仅在不同按钮时复原颜色
                    WeiLe.gBtn.setBackgroundColor(0xff2177b8);   // 复原颜色
                }
                WeiLe.gQid = 5;
                WeiLe.gBtn = mBtn5;
                mBtn5.setBackgroundColor(Color.GRAY);
                mBtn5.setText(String.valueOf(WeiLe.gAnswer[5]));
                if (mQ[5] != null) {
                    mTvQuestions.setText(mQ[5]);
                }
                mTvBody.setMaxLines(mMaxLines);
                mTvBody.setMaxWidth(mMaxWidth);
                mTvQuestions.setMaxWidth(mMaxWidth);
            }
        });
        btn = root.findViewById(R.id.btnSubmit);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int cntWrong = 0;
                // not done
                if (WeiLe.gAnswer[1] != mA[1]) {
                    cntWrong += 1;
                    mBtn1.setBackgroundColor(0xffee3f4d);
                }
                else{
                    mBtn1.setBackgroundColor(0xff229453);
                }
                if (WeiLe.gAnswer[2] != mA[2]) {
                    cntWrong += 1;
                    mBtn2.setBackgroundColor(0xffee3f4d);
                }
                else{
                    mBtn2.setBackgroundColor(0xff229453);
                }
                if (WeiLe.gAnswer[3] != mA[3]) {
                    cntWrong += 1;
                    mBtn3.setBackgroundColor(0xffee3f4d);
                }
                else{
                    mBtn3.setBackgroundColor(0xff229453);
                }
                if (WeiLe.gAnswer[4] != mA[4]) {
                    cntWrong += 1;
                    mBtn4.setBackgroundColor(0xffee3f4d);
                }
                else{
                    mBtn4.setBackgroundColor(0xff229453);
                }
                if (WeiLe.gAnswer[5] != mA[5]) {
                    cntWrong += 1;
                    mBtn5.setBackgroundColor(0xffee3f4d);
                }
                else{
                    mBtn5.setBackgroundColor(0xff229453);
                }
                // 特殊的初始化，让你必须要单独判断?
                WeiLe.mainActivity.showToast("一共5道题，你错啦" + cntWrong + "题，加油！");
            }
        });

        // others
        List<String> listFiles = LewayHelper.getRawFiles(WeiLe.mainActivity);
        WeiLe.gRawFiles.clear();
        WeiLe.gRawFiles.add("请选择"); // 添加默认选项
        WeiLe.gRawFiles.add("自定义题目");
        for (int i = 0; i < listFiles.size(); i++) {
            if (listFiles.get(i).contains("english")) {
                WeiLe.gRawFiles.add(listFiles.get(i));
            }
            WeiLe.gLogText += TS() + listFiles.get(i) + "\n";
        }

        // 获取cbSpinner组件
        Spinner cbSpinner = root.findViewById(R.id.cbSpinner);
        // 创建一个ArrayAdapter实例
        ArrayAdapter<CharSequence> adapter =
                new ArrayAdapter<>(WeiLe.mainActivity, android.R.layout.simple_list_item_1,
                        WeiLe.gRawFiles.toArray(new String[WeiLe.gRawFiles.size()]));
        WeiLe.gLogText += TS() + "size=" + WeiLe.gRawFiles.size() + "\n";
        // 将adapter设置给Spinner
        cbSpinner.setAdapter(adapter);

        // 添加监听器
        cbSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selected = parent.getItemAtPosition(position).toString();
                if (!selected.equals("请选择")) { // 排除默认选项
                    WeiLe.gLogText += TS() + selected + "\n";
                    bodyAppend(LewayHelper.readRawFile(WeiLe.mainActivity, selected));

                    // 处理完选择后，重置 Spinner 选择回默认选项
                    parent.setSelection(0);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 当没有选项被选中时的回调
            }
        });

        Spinner abcdSpinner = root.findViewById(R.id.abcdSpinner);
        // 假设 abcdSpinner 的数据源已经包含 "请选择" 作为第一个选项
        ArrayAdapter<CharSequence> abcdAdapter =
                new ArrayAdapter<>(WeiLe.mainActivity, android.R.layout.simple_spinner_item,
                        new String[]{"请选择", "A", "B", "C", "D"});
        abcdAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        abcdSpinner.setAdapter(abcdAdapter);

        abcdSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selected = parent.getItemAtPosition(position).toString();
                if (!selected.equals("请选择")) { // 排除默认选项
                    WeiLe.gLogText += TS() + selected + "\n";
                    if ((1 <= WeiLe.gQid) && (WeiLe.gQid <= 5)) {
                        if (selected.equals("单选")) {
                            WeiLe.gAnswer[WeiLe.gQid] = '?';
                            WeiLe.gBtn.setText(String.valueOf('?'));
                        } else {
                            WeiLe.gAnswer[WeiLe.gQid] = selected.charAt(0);
                            WeiLe.gBtn.setText(selected);
                        }
                    } else {
                        WeiLe.gLogText += TS() + "illegal qId " + WeiLe.gQid + "\n";
                    }

                    // 重置 Spinner 选择回默认选项
                    parent.setSelection(0);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 当没有选项被选中时的回调
            }
        });

        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mMaxLines == 0) {
            if (mTvBody.getHeight() != 0) {
                mMaxLines = mTvBody.getHeight() / mTvBody.getLineHeight();
                mTvBody.setMaxLines(mMaxLines);
            }
        } else {
            mTvBody.setMaxLines(mMaxLines);
        }
        if (mMaxWidth == 0) {
            if (mTvBody.getHeight() != 0) {
                mMaxWidth = mTvBody.getWidth();
                mTvBody.setMaxWidth(mMaxWidth);
            }
        } else {
            mTvBody.setMaxWidth(mMaxWidth);
        }
        WeiLe.gLogText += TS() + mTvBody.getHeight() + " height Resume\n";
        WeiLe.gLogText += TS() + mTvBody.getMaxHeight() + " maxHeight Resume\n";
        WeiLe.gLogText += TS() + mTvBody.getLineHeight() + " lineHeight Resume\n";
        WeiLe.gLogText += TS() + mMaxLines + " maxLines Resume\n";
        WeiLe.gLogText += TS() + mMaxWidth + " maxWidth Resume\n";
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (mMaxLines == 0) {
                    mMaxLines = mTvBody.getHeight() / mTvBody.getLineHeight();
                    mTvBody.setMaxLines(mMaxLines);
                }
                if (mMaxWidth == 0) {
                    mMaxWidth = mTvBody.getWidth();
                    mTvBody.setMaxWidth(mMaxWidth);
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

}
